package cn.zt.middleware.dynamic.thread.pool.sdk.registry.redis;

import cn.zt.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.zt.middleware.dynamic.thread.pool.sdk.domain.model.valobj.RegistryEnumVO;
import cn.zt.middleware.dynamic.thread.pool.sdk.registry.IRegistry;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.List;

/**
 * @author: zhangtao
 * @description: Redis 注册中心
 * @date: 2024-08-09 14:39
 */

public class RedisRegistry implements IRegistry {


    private final RedissonClient redissonClient;

    public RedisRegistry(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 批量上报线程池配置
     */
    @Override
    public void reportThreadPoolConfigList(List<ThreadPoolConfigEntity> threadPoolConfigEntities) {
        // 1. 先获取
        RList<ThreadPoolConfigEntity> list = redissonClient.getList(RegistryEnumVO.THREAD_POOL_CONFIG_LIST_KEY.getKey());
        // 2. 再删除
        list.delete();
        // 3. 最后更新
        list.addAll(threadPoolConfigEntities);

    }

    /**
     * 上报线程池配置
     */
    @Override
    public void reportThreadPoolConfig(ThreadPoolConfigEntity config) {
        String cacheKey = RegistryEnumVO.THREAD_POOL_CONFIG_PARAMETER_LIST_KEY.getKey()
                + "_" + config.getAppName() + "_" + config.getThreadPoolName();
        RBucket<ThreadPoolConfigEntity> bucket = redissonClient.getBucket(cacheKey);
        bucket.set(config, Duration.ofDays(30));
    }
}
